package com.aote.entity.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.aote.component.format.FormatFactory;
import com.aote.mvc.event.Action;
import com.aote.util.ExpressionHelper;
import com.aote.util.StringHelper;
import com.browsesoft.Entity;
import com.browsesoft.EntityManager;
import com.browsesoft.baseadapter.AdvancedSimpleEntity;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.user.User;

/**
 * 根据配置的表达式，回写管理对象属性的动作
 */
public class WriteReturnValueAction extends Action {
	/**
	 * 对应的模型
	 */
	private AdvancedSimpleEntity model;

	/**
	 * 设置组件时，取出模型
	 */
	public void setComponent(HTMLBasicComponent component) {
		super.setComponent(component);
		this.model = (AdvancedSimpleEntity) component.getModel();
	}

	public void performAction(Element config, HttpServletRequest request,
			Map attrs) {
		// 对于每一个要回写的对象
		NodeList nl = config.getElementsByTagName("return");
		for (int i = 0; i < nl.getLength(); i++) {
			Element e = (Element) nl.item(i);
			// 得到回写框名称，根据名称，得到回写实体
			String name = e.getAttribute("name");
			Entity entity = this.getEntity(name);
			// 如果条件不满足,跳过该实体
			Map con = this.getCondition(e);
			if (con.size() > 0 && !EntityManager.isSame(entity, con)) {
				continue;
			}
			// 得到数据集合,source="this"或类名
			Map temp = getSourceDataMap(e);
			if (temp != null) {
				// 给实体回写数据
				this.writeOneEntity(entity, e, request, temp);
			} else {
				// 给实体回写数据
				this.writeOneEntity(entity, e, request, attrs);
			}

		}
	}

	/**
	 * 得到条件
	 */
	public Map getCondition(Element e) {
		Map result = new HashMap();
		NodeList nl = e.getElementsByTagName("condition");
		for (int i = 0; i < nl.getLength(); i++) {
			Element ce = (Element) nl.item(i);
			String name = ce.getAttribute("name");
			String value = ce.getAttribute("value");
			result.put(name, value);
		}
		return result;
	}

	private Map getSourceDataMap(Element elem) {
		if (!elem.hasAttribute("source")) {
			return null;
		}
		String sourceName = elem.getAttribute("source");
		Entity entity = this.getEntity(sourceName);
		if (entity == null) {
			return null;
		}
		return entity.getAttributes();
	}

	/**
	 * 得到回写实体
	 */
	private Entity getEntity(String name) {
		// 如果是this，给模型回写
		if (name.equals("this")) {
			return model;
		} else {
			Entity entity = model.getEntity(name);
			return entity;
		}
	}

	/**
	 * 根据配置，回写某个回写实体的数据
	 */
	private void writeOneEntity(Entity entity, Element config,
			HttpServletRequest request, Map attrs) {
		throw new UnsupportedOperationException();
	}
}
